/**
 * react-dnd 拖拽组件中的容器组件
 * @props style 样式 - object
 * @props DragTypeString 拖拽的类型，用以和拖拽组件进行匹配 - string
 * @props children 拖拽组件的子节点 - node
 * @props endDrag 拖拽结束后返回的方法 - func
 */

import { useCallback } from 'react'
import { useDrop } from 'react-dnd'
import PropsType from "prop-types";

const DraggableContainer = ({ style, DragTypeString, children, endDrag }) => {
  const moveBox = useCallback(
    (item, left, top) => {
      endDrag(item, left, top)
    },
    [endDrag],
  )
  const [, drop] = useDrop(
    () => ({
      accept: DragTypeString,
      drop(item, monitor) {
        const delta = monitor.getDifferenceFromInitialOffset()
        const left = Math.round(item.left + delta.x)
        const top = Math.round(item.top + delta.y)
        moveBox(item, left, top)
        return undefined
      },
    }),
    [moveBox],
  )
  return (
    <div ref={drop} style={{position: 'relative', ...style}}>
      {children}
    </div>
  )
}

DraggableContainer.propTypes = {
  style: PropsType.object,
  DragTypeString: PropsType.string.isRequired,
  children: PropsType.node,
  endDrag: PropsType.func.isRequired
}

export default DraggableContainer
